package com.deschen.security.core.social.weixin.api;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author deschen
 * @Create 2019/9/9
 * @Description spring social第三方微信登入中获取用户信息接口实现类
 * @Since 1.0.0
 */
// 微信文档：https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
public class WeixinImpl extends AbstractOAuth2ApiBinding implements Weixin {

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * http：GET（请使用https协议） https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
     * 参数	描述
     * access_token	网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
     * openid	用户的唯一标识
     * lang	返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
     * @param openId
     * @return
     */
    private static final String GET_USER_INFO_URL =
            "https://api.weixin.qq.com/sns/userinfo?openid=%s&lang=zh_CN";

    public WeixinImpl(String accessToken) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        // 忽略json转换vo缺少相应属性报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 创建restTemplate默认处理返回的text-html格式，但是是“ISO-8859-1”,微信返回UTF-8，必须覆盖
     * @return
     */
    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        // 继承的配置，第一个就是处理html与String处理，移除配置新的
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return messageConverters;
    }

    /**通过链接获取微信用户信息
     * https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
     * @param openId
     * @return
     */
    @Override
    public WeixinUserInfo getWeixinUserInfo(String openId) {
        String getUserInfoUrl = String.format(GET_USER_INFO_URL, openId);
        String userInfoResponse = getRestTemplate().getForObject(getUserInfoUrl, String.class);
        // 判断是否放回错误码
        if (StringUtils.contains(userInfoResponse, "errcode")) {
            return null;
        }
        WeixinUserInfo weixinUserInfo = null;
        try {
            weixinUserInfo = objectMapper.readValue(userInfoResponse, WeixinUserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return weixinUserInfo;
    }
}
